package com.cee.http;

import com.cee.util.JsonUtil;

import com.cee.util.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * http请求工具类
 * @author zhuzhe
 * @date 2018/5/3 11:46
 */
public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static RestTemplateBuilder httpsRestTemplateBuilder = null;
 
    /**
     * get
     *
     * @param host
     * @param path
     *
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        return httpClient.execute(request);
    }

    public static HttpResponse doGet(String path,
                                     Map<String, String> params)
            throws Exception {
        HttpClient httpClient = wrapClient(null,path);
        HttpGet request = new HttpGet(buildUrl(null, path, params));
        return httpClient.execute(request);
    }
 
    /**
     * post form
     *
     * @param host
     * @param path
     *
     * @param headers
     * @param params
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path,
                                      Map<String, String> headers,
                                      Map<String, String> params,
                                      Map<String, String> body)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpPost request = new HttpPost(buildUrl(host, path, params));

        setHeaders(headers, request);
        if (body != null) {
            StringEntity entity = new StringEntity(JsonUtil.format(body), "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            request.setEntity(entity);
        }
        return httpClient.execute(request);
    }

    public static HttpResponse doPost(String path,
                                     Map<String, String> params)
            throws Exception {
        HttpClient httpClient = wrapClient(null,path);
        HttpPost request = new HttpPost(buildUrl(null, path, params));
        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     *
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        setHeaders(headers, request);
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
    }
 
    /**
     * Post stream
     *
     * @param host
     * @param path
     *
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        setHeaders(headers, request);
        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
    }
 
    /**
     * Put String
     * @param host
     * @param path
     *
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpPut request = new HttpPut(buildUrl(host, path, querys));

        setHeaders(headers, request);
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
    }
 
    /**
     * Put stream
     * @param host
     * @param path
     *
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpPut request = new HttpPut(buildUrl(host, path, querys));

        setHeaders(headers, request);
        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
    }
 
    /**
     * Delete
     *
     * @param host
     * @param path
     *
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));

        setHeaders(headers, request);
        return httpClient.execute(request);
    }

    private static void setHeaders(Map<String, String> headers, HttpRequestBase request) {
        if (headers != null) {
            for (Map.Entry<String, String> e : headers.entrySet()) {
                request.addHeader(e.getKey(), e.getValue());
            }
        }
    }

    /**
     * 构建请求的 url
     * @param host
     * @param path
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String buildUrl(String host, String path, Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        if (!StringUtils.isBlank(host)) {
            sbUrl.append(host);
        }
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != params) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : params.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        return sbUrl.toString();
    }
 
    /**
     * 获取 HttpClient
     * @param host
     * @param path
     * @return
     */
    private static HttpClient wrapClient(String host,String path) {
        if (host != null && host.startsWith("https://")) {
            return sslClient();
        } else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {
            return sslClient();
        }
        HttpClient httpClient = HttpClientBuilder.create().build();
        return httpClient;
    }
 
    /**
     * 在调用SSL之前需要重写验证方法，取消检测SSL
     * 创建ConnectionManager，添加Connection配置信息
     * @return HttpClient 支持https
     */
    private static HttpClient sslClient() {
        try {
            // 在调用SSL之前需要重写验证方法，取消检测SSL
            X509TrustManager trustManager = new X509TrustManager() {
                @Override public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override public void checkClientTrusted(X509Certificate[] xcs, String str) {}
                @Override public void checkServerTrusted(X509Certificate[] xcs, String str) {}
            };
            SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            ctx.init(null, new TrustManager[] { trustManager }, null);
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            // 创建Registry
            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                    .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
                    .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https",socketFactory).build();
            // 创建ConnectionManager，添加Connection配置信息
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
                    .setDefaultRequestConfig(requestConfig).build();
            return closeableHttpClient;
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Gets rest template.
     *
     * @return the rest template
     */
    public static RestTemplate getRestTemplate(URI uri) {
        boolean https = false;
        try {
            https = uri.toURL().getProtocol().contains("https");
        } catch (MalformedURLException e) {
            logger.error(e.toString());
        }
        if (https) {
            if (httpsRestTemplateBuilder == null) {
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
                requestFactory.setHttpClient(sslClient());
                RestTemplateBuilder restTemplateBuilder = SpringContextUtil.getBean(RestTemplateBuilder.class);
                httpsRestTemplateBuilder = restTemplateBuilder.requestFactory(new Supplier<ClientHttpRequestFactory>() {
                    @Override
                    public ClientHttpRequestFactory get() {
                        return requestFactory;
                    }
                });
            }
            return httpsRestTemplateBuilder.build();
        }
        return SpringContextUtil.getBean(RestTemplateBuilder.class).build();
    }

    public static HttpResult getHttpResult(Class<?> valueType, HttpResponse response) throws IOException {
        String content = EntityUtils.toString(response.getEntity(), "utf-8");
        logger.debug("content: {}", content);
        if (valueType == null) {
            return new HttpResult(response.getStatusLine().getStatusCode(), content);
        } else {
            return new HttpResult(
                    response.getStatusLine().getStatusCode(), JsonUtil.parse(content, valueType));
        }
    }

    public static HttpResult doPost(String url, Map<String, String> header, String json, Class<?> valueType) throws Exception {
        Map<String, String> bodys = new HashMap<>();
        if (json != null) {
            Map<String, Object> map = JsonUtil.parse(json, Map.class);
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                bodys.put(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : null);
            }
        }

        HttpResponse httpResponse = HttpUtils.doPost(url, null, header, null, bodys);
        return getHttpResult(valueType, httpResponse);
    }

    public static HttpResult doPost(String url, String json, Class<?> valueType) throws Exception {
        return doPost(url, null, json, valueType);
    }

    public static HttpResult doPost(String url, Map<String, Object> map, Class<?> valueType) throws Exception {
        Map<String, String> bodys = new HashMap<>();
        if (map != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                bodys.put(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : null);
            }
        }

        HttpResponse httpResponse = HttpUtils.doPost(url, null, null, null, bodys);
        return getHttpResult(valueType, httpResponse);
    }


}